<?php
/**
 * 单例模式连接数据库
 * @author dell
 *
 */
class DB{
    static private $instance;//静态成员变量，单例模式标准
    static private $_connectSource;
    private $_dbConfig = array(
      'host'=>'127.0.0.1',
      'user'=>'root',
      'password'=>'root',
      'database'=>'shopImooc'
    );
    
    private function _construct(){
        
    }
    static public function getInstance(){
        //访问这个实例的公共的静态方法
        if (!self::$instance instanceof self){
            //判断是否已经实例化
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function connect(){
        if (!self::$_connectSource){//减少资源浪费
            self::$_connectSource = @mysql_connect($this->_dbConfig['host'],$this->_dbConfig['user'],$this->_dbConfig['password']);
            //返回资源句柄
            if(!self::$_connectSource){
                throw new Exception('mysql connect error'.mysql_error());
                //抛出异常
                //die('mysql connect error'.mysql_errno());
            
            }
            mysql_select_db($this->_dbConfig['database'],self::$_connectSource);
            //查询数据库
            mysql_query("set names UTF8",self::$_connectSource);
            //设置字符集
         }
        return self::$_connectSource;
    }
}

// $connect = DB::getInstance()->connect();
// $sql = "select * from imocc_admin";
// $result = mysql_query($sql,$connect);
// echo mysql_num_rows($result);
// var_dump($result);
